﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using DevComponents.AdvTree;
using DevComponents.DotNetBar;
using PlanningGIS.ManageUtility;
using PlanningGIS.ManageUtility.Modules;
using PlanningGIS.Win.Controls;
using PlanningGIS.Util.Log;
using PlanningGIS.Framework;
using PlanningGIS.Util;

namespace PlanningGIS.Manager
{
    /// <summary>
    /// 功能菜单配置
    /// </summary>
    public partial class CtlFuncCfg : UserControl
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public CtlFuncCfg()
        {
            InitializeComponent();
            Init();
        }
        /// <summary>
        /// 
        /// </summary>
        private bool _Listening = false;
        /// <summary>
        /// 初始化
        /// </summary>
        private void Init()
        {
            List<ValueName> btnstyles = new List<ValueName>();
            btnstyles.Add(new ValueName()
            {
                Name = PlanningGIS.ManageUtility.eButtonStyle.ImageAndText.GetDescription(),
                Value = PlanningGIS.ManageUtility.eButtonStyle.ImageAndText.ToString()
            });
            btnstyles.Add(new ValueName()
            {
                Name = PlanningGIS.ManageUtility.eButtonStyle.Image.GetDescription(),
                Value = PlanningGIS.ManageUtility.eButtonStyle.Image.ToString()
            });
            btnstyles.Add(new ValueName()
            {
                Name = PlanningGIS.ManageUtility.eButtonStyle.Text.GetDescription(),
                Value = PlanningGIS.ManageUtility.eButtonStyle.Text.ToString()
            });
            cmbStyle.ValueMember = "Value";
            cmbStyle.DisplayMember = "Name";
            cmbStyle.DataSource = btnstyles;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="type">1:func; 2:toc ;</param>
        public void InitControl(int type)
        {
            btnView.Visible = type == 1 ? true : false;
            btnAddMenu.Visible = type == 1 ? true : false;
            //swtbtnDirection.Value = type == 1 ? true : false;
            swtbtnDirection.Enabled = type == 1 ? true : false;
            
        }
        /// <summary>
        /// 加载DLL
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLoadDll_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.InitialDirectory = Application.StartupPath;
            dlg.Filter = ".net组件(*.dll)|*.dll";
            dlg.RestoreDirectory = true;
            dlg.Multiselect = true;
            if (dlg.ShowDialog(this.ParentForm) != DialogResult.OK) return;
            treeDll.Nodes.Clear();
            string[] filenames = dlg.FileNames;
            try
            {
                foreach (string filename in filenames)
                {
                    Assembly assembly = Assembly.LoadFile(filename);
                    Type[] types = assembly.GetTypes();
                    foreach (Type type in types)
                    {
                        if (type.GetInterface("ICommand") == null || type.IsSubclassOf(typeof(System.Windows.Forms.Form))) continue;
                        string namespacestr = type.Namespace;
                        Node[] nodes = treeDll.Nodes.Find(namespacestr, true);
                        Node treeNode = null;
                        if (nodes == null || nodes.Length == 0)
                        {
                            treeNode = new Node(namespacestr);
                            treeNode.Name = namespacestr;
                            treeNode.Tooltip = type.FullName + "," + type.Assembly.GetName().Name;
                            treeNode.ImageIndex = 4;
                            treeDll.Nodes.Add(treeNode);
                        }
                        else
                        {
                            treeNode = nodes[0];
                        }
                        try
                        {
                            object obj = Activator.CreateInstance(type);
                            Node subNode = new Node();
                            subNode.Text = type.Name;
                            List<string> txts = new List<string>() { "Caption", "ICommand.Caption", "Text", "Name" };
                            foreach (string txt in txts)
                            {
                                PropertyInfo pi = type.GetProperty(txt, typeof(string));
                                if (pi == null) continue;
                                object value = pi.GetValue(obj, null);
                                if (value == null || string.IsNullOrWhiteSpace(value.ToString())) continue;
                                subNode.Text = value.ToString().Trim();
                                break;
                            }
                            if (type.BaseType.FullName == "DevComponents.DotNetBar.Bar")
                            {
                                subNode.ImageIndex = 0;                                
                                subNode.Tooltip = type.ToString();
                                PrivilegeGroup group = new PrivilegeGroup();
                                group.Enable = true;
                                group.Text = subNode.Text;
                                group.TypeName = type.FullName + "," + type.Assembly.GetName().Name;
                                subNode.Tag = group;
                            }
                            else
                            {
                                string[] imgs = Directory.GetFiles(AppConfig.ImagePath + "\\32X32", subNode.Text + ".*", SearchOption.AllDirectories);
                                if (imgs == null || imgs.Length == 0)
                                {
                                    subNode.Image = ResourcesHelper.GetImage("Button.Tools.png");
                                    PropertyInfo pi = type.GetProperty("Bitmap", typeof(string));
                                    if (pi != null)
                                    {
                                        object value = pi.GetValue(obj, null);
                                        if (value != null && value.ToString() != "0")
                                            subNode.Image = System.Drawing.Bitmap.FromHbitmap((IntPtr)value);
                                    }
                                }
                                else
                                    subNode.Image = new Bitmap(imgs[0]);
                                subNode.Tooltip = type.FullName + "," + type.Assembly.GetName().Name;
                                Privilege privilege = new Privilege();
                                privilege.Enable = true;
                                privilege.Text = subNode.Text;
                                privilege.TypeName = type.FullName + "," + type.Assembly.GetName().Name;
                                subNode.Tag = privilege;
                            }
                            treeNode.Nodes.Add(subNode);
                        }
                        catch (Exception ex)
                        {
                            LogHelper.WriteErrorText(ex);
                        }
                    }

                }
            }
            catch (System.Exception ex)
            {
                MsgHelper.ShowWarningMsgbox("加载组件失败，该组件无效:" + ex.ToString());
            }
        }

        /// <summary>
        /// 导入Xml功能配置文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnImpXml_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "XML文件|*.xml";
            dlg.InitialDirectory = Application.StartupPath;
            dlg.Multiselect = false;
            if (dlg.ShowDialog(this.ParentForm) != DialogResult.OK) return;
            funcTree1.Nodes.Clear();
            funcTree1.ReadFile(dlg.FileName);
        }

        /// <summary>
        /// 导出Xml功能配置文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExpXml_Click(object sender, EventArgs e)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.Filter = "XML文件|*.xml";
            dlg.FilterIndex = 1;
            dlg.RestoreDirectory = true;
            dlg.Title = "导出到XML文件";
            if (dlg.ShowDialog(this.ParentForm) != DialogResult.OK) return;
            funcTree1.ExportXml(dlg.FileName);
        }

        /// <summary>
        /// 启用所有功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUsing_Click(object sender, EventArgs e)
        {
            funcTree1.SetEnableAll(true, funcTree1.Nodes);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStartChild_Click(object sender, EventArgs e)
        {
            if (funcTree1.SelectedNode == null) return;
            funcTree1.SetEnableAll(true, funcTree1.SelectedNode.Nodes);
        }

        /// <summary>
        /// 清除所有菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClear_Click(object sender, EventArgs e)
        {
            funcTree1.Nodes.Clear();
        }

        /// <summary>
        /// 添加子节点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddChild_Click(object sender, EventArgs e)
        {
            if (funcTree1.Nodes.Count == 0 || funcTree1.SelectedNode == null) return;
            funcTree1.AddMenu(funcTree1.SelectedNode.Nodes);
        }

        /// <summary>
        /// 删除菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (funcTree1.Nodes.Count == 0 || funcTree1.SelectedNode == null) return;
            DialogResult dlg = MsgHelper.ShowYesOrNoQueryMsgBox("是否确定要移除选择的菜单项？");
            if (dlg != DialogResult.Yes) return;
            try
            {
                List<Node> nds = new List<Node>();
                foreach (Node n in funcTree1.SelectedNodes)
                {
                    nds.Add(n);
                }
                foreach (Node n in nds)
                {
                    //Node n1 = funcTree1.FindNodeByName(n.Name);
                    //if (n1 == null) continue;
                    if (n.Parent != null) n.Parent.Nodes.Remove(n);
                    else funcTree1.Nodes.Remove(n);
                    //funcTree1.Nodes.Remove(n);
                    //funcTree1.Nodes.Remove()
                }

            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox(ex.Message);
            }
            
        }

        /// <summary>
        /// 添加菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddMenu_Click(object sender, EventArgs e)
        {
            if (funcTree1.Nodes.Count == 0 ) return;
            funcTree1.AddMenu(funcTree1.Nodes);
        }

        /// <summary>
        /// 保存功能配置
        /// </summary>
        /// <param name="key"></param>
        public void Save(string key)
        {
            Hash_Table p = new Hash_Table()
            {
                Key = key,
                Value = System.Text.Encoding.UTF8.GetBytes(funcTree1.GetXml())
            };
            
            try
            {
                bool isnew = false;
                if (ManageHelper.Hash_Tables == null ||
                    ManageHelper.Hash_Tables.Count == 0 ||
                    !ManageHelper.Hash_Tables.Exists(t => t.Key.Equals(key, StringComparison.CurrentCultureIgnoreCase)))
                    isnew = true;
                int rst = 0;
                if (isnew) rst = ManageHelper.DBContext.Insert<Hash_Table>(p);
                else rst = ManageHelper.DBContext.Update<Hash_Table>(p, "key", p.Key);
                if (rst > 0)
                {
                    if (!isnew)
                    {
                        Hash_Table o = ManageHelper.Hash_Tables.FirstOrDefault(t => t.Key.Equals(key, StringComparison.CurrentCultureIgnoreCase));
                        if (o != null) o.Value = p.Value;
                    }
                    MsgHelper.ShowInfomationMsgbox("操作成功");
                }
                else MsgHelper.ShowErrorMsgbox("操作失败");
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox(ex.ToString());
            }

        }

        /// <summary>
        /// 读取Xml配置
        /// </summary>
        /// <param name="xml"></param>
        public void ReadXml(string xml)
        {
            funcTree1.ReadXml(xml);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void funcTree1_AfterCheck(object sender, AdvTreeCellEventArgs e)
        {
            if (e.Action == eTreeAction.Mouse)
            {
                if (funcTree1.SelectedNode == null) return;
                swtbtnEnable.Value = (funcTree1.SelectedNode.CheckState != CheckState.Unchecked) ? true : false;
            }
        }

        /// <summary>
        /// 节点选择改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void funcTree1_AfterNodeSelect(object sender, AdvTreeNodeEventArgs e)
        {
            try
            {
                if (funcTree1.SelectedNode == null) return;
                BindInfo(funcTree1.SelectedNode);
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox(ex.ToString());
            }
            
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="node"></param>
        private void BindInfo(Node node)
        {
            if (node == null) return;
            _Listening = false;
            IPrivilegeElement p = (IPrivilegeElement)node.Tag;
            txtName.Text = p.NakedText;
            txtName.Tag = node;
            txtKJJ.Text = p.KeyTips;
            swtbtnEnable.Value = p.Enable;
            swtbtnDirection.Value = p.VerticalShow;
            swtbtnGroup.Value = p.BeginGroup;
            cmbStyle.SelectedValue = p.ButtonStyle.ToString();
            string name = p.NakedText.Replace("/", "");
            string[] imgs = Directory.GetFiles(AppConfig.ImagePath + "\\32X32", name + ".*", SearchOption.AllDirectories);
            if (imgs != null && imgs.Length > 0)
                picImage.Image = new Bitmap(imgs[0]);
            else
                picImage.Image = ResourcesHelper.GetImage("Button\\Tools.png");
            _Listening = true;
        }

        /// <summary>
        /// 双击选择图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void picImage_DoubleClick(object sender, EventArgs e)
        {
            OpenFileDialog _dlg = new OpenFileDialog
            {
                Filter = "常见图片|*.jpg;*.gif;*.png;*.bmp"
            };
            if (_dlg.ShowDialog() != DialogResult.OK) return;
            picImage.Image = Image.FromFile(_dlg.FileName);
        }

        /// <summary>
        /// 分组选择改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void swtbtnGroup_ValueChanged(object sender, EventArgs e)
        {
            if (funcTree1.SelectedNode == null || !_Listening) return;
            ((IPrivilegeElement)funcTree1.SelectedNode.Tag).BeginGroup = swtbtnGroup.Value;
        }

        /// <summary>
        /// 方向选择改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void swtbtnDirection_ValueChanged(object sender, EventArgs e)
        {
            if (funcTree1.SelectedNode == null || !_Listening) return;
            ((IPrivilegeElement)funcTree1.SelectedNode.Tag).VerticalShow = swtbtnDirection.Value;
        }

        /// <summary>
        /// 启用选择改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void swtbtnEnable_ValueChanged(object sender, EventArgs e)
        {
            if (funcTree1.SelectedNode == null || !_Listening) return;
            funcTree1.SelectedNode.Checked = swtbtnEnable.Value;
            ((IPrivilegeElement)funcTree1.SelectedNode.Tag).Enable = swtbtnEnable.Value;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmbStyle_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (funcTree1.SelectedNode == null || !_Listening) return;
            ((IPrivilegeElement)funcTree1.SelectedNode.Tag).ButtonStyle = (PlanningGIS.ManageUtility.eButtonStyle)Enum.Parse(typeof(PlanningGIS.ManageUtility.eButtonStyle), cmbStyle.SelectedValue.ToString());
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtName_TextChanged(object sender, EventArgs e)
        {
            if (funcTree1.SelectedNode == null || !_Listening) return;
            ((IPrivilegeElement)funcTree1.SelectedNode.Tag).Text = txtName.Text;
            funcTree1.SelectedNode.Text = txtName.Text;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtKJJ_TextChanged(object sender, EventArgs e)
        {
            if (funcTree1.SelectedNode == null || !_Listening) return;
            ((IPrivilegeElement)funcTree1.SelectedNode.Tag).KeyTips = txtKJJ.Text;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnView_Click(object sender, EventArgs e)
        {
            funcTree1.ViewMenus();
        }

    }
}
